package com.sykj.bsc.cl.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.sykj.bsc.cl.bean.WechatUser;
import com.sykj.bsc.cl.service.WechatCommonService;
import com.sykj.bsc.constant.WechatCons;
import com.sykj.bsc.util.PropUtil;
import com.sykj.bsc.util.SignUtil;
import com.sykj.bsc.util.WechatUtil;
import com.sykj.bsc.zjj.bean.Bis_custom_user;

@Controller
@RequestMapping("wechatCore")
public class WechatCoreController {

	@Autowired
	private WechatCommonService wechatService;
	@RequestMapping(value="subscribe", method = RequestMethod.GET)
	@ResponseBody
	public String subscribeGet(@RequestParam(value = "signature") String signature,
			@RequestParam(value = "timestamp") String timestamp,
			@RequestParam(value = "nonce") String nonce,
			@RequestParam(value = "echostr") String echostr,HttpServletRequest request,HttpServletResponse response) {
		//获取token
		String token=PropUtil.getString("wechat.token");
		//微信验证登陆
		if(SignUtil.checkSignature(token,signature,
				timestamp, nonce)){
			return echostr;
		}
		return "";
	}
	
	@RequestMapping(value = "initLogin")
	public  ModelAndView initLogin(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {
		System.out.println("跳转地址：" + "wechatCore/goWechatLogin");
		response.sendRedirect(WechatUtil.getOauth2Url("wechatCore/goWechatLogin",WechatCons.GRANT_YES));
		return null;
	}
	
	@RequestMapping(value = "goWechatLogin")
	public  String goWechatLogin(String code,HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {
		String rootPath=request.getSession().getServletContext().getRealPath("/");
		WechatUser wechatUser=WechatUtil.getOAuthUserInfo(code);
		Bis_custom_user customUser=wechatService.saveCustomInfo(wechatUser, rootPath);
		session.setAttribute("customUser",customUser);
		return "redirect:"+PropUtil.getString("wechat.server")+"/wechat/login";
	}
}
